#include "gwlib/gw_login.h"

#include <json/json.h>
#include <gwbase/base/logging.h>
#include <gwbase/curl_wrapper.h>
#include <gwbase/http_util.h>

namespace dicom {

bool ParseGwTokenJson(const std::string& s, GwToken* t) {
  Json::Value v;
  Json::Reader reader;
  if (!reader.parse(s, v, false))
    return false;

  if (v["code"].asInt() != 0) {
    return false;
  }

  t->token = v["token"].asString();
  return true;
}

int Login(const std::string& server,
          const std::string& user,
          const std::string& password,
          const std::string& ukey_id,
          GwToken** t)
{
  dicom::EasyCurl curl;

  std::string url = server + "/api/login?";
  AppendQueryString(&url, "name", user);
  AppendQueryString(&url, "password", password);
  AppendQueryString(&url, "ukey_id", ukey_id);

  curl.SetUrl(url);
  std::string response;
  curl.EnableDebugOutput(true);
  bool ret = curl.PerformText(&response);

  if (!ret || curl.http_status() != 200) {
    return -1;
  }

  LOG_INFO << "response: " << response;

  GwToken* gt = new GwToken();
  gt->server = server;
  if (ParseGwTokenJson(response, gt) == false) {
    delete gt;
    return -1;
  }

  LOG_INFO << "token: " << gt->token;

  (*t) = gt;
  return 0;
}

int LogoutAndReleaseToken(GwToken* t) {
  dicom::EasyCurl curl;

  std::string url = t->server + "/api/logout";
  CurlHeaders headers;
  headers.AddOAuthHeader(t->token);
  curl.AddHeaders(&headers);

  curl.SetUrl(url);
  std::string response;
  bool ret = curl.PerformText(&response);
  if (!ret || curl.http_status() != 200) {
    return -1;
  }

  delete t;
  return 0;
}

}
